import { useMenuList } from "@/store/modules/menuList";
import allRoute from "../pageRoute";
import api from '@/services/api/home'

export const getMenuList = async (params) => {
  let { menusList } = await api.menu();
  let { menuArr, menuObj } = getMenuArr(menusList);
  let routeList = getRoute(allRoute, menuArr)

  let finallRoute = finalRoute(routeList, menuObj)

  const menuStore = useMenuList();
  menuStore.changeMenuList(finallRoute);
  return finallRoute;
};

//获取接口权限路由数组
function getMenuArr (menusList) {
  let menuArr = []
  let menuObj = {}
  menusList.forEach(item => {
    menuArr.push(item.path);
    menuObj[item.path] = { title: item.title || '', meta: { limit: item.limit || [] }, icon: item.icon || 'icon-sort' }
  });

  return { menuArr: menuArr, menuObj: menuObj }
}

//获取存在的路由
function getRoute (allRoute, menuArr) {
  let route = []
  allRoute.forEach(item => {
    if (menuArr.indexOf(item.path) !== -1) {
      if (item.children) {
        let child = getRoute(item.children, menuArr);
        route.push({
          path: item.path, name: item.name, children: child
        })
      } else {
        route.push(item)
      }
    }
  });
  return route;
}
//获取最终路由
function finalRoute (routeList, menuObj) {
  let route = [];
  routeList.forEach(item => {
    if (item.children) {
      let child = finalRoute(item.children, menuObj);
      route.push({ name: item.name, path: item.path, children: child, ...menuObj[item.path] })
    } else {
      route.push({ ...item, ...menuObj[item.path] })
    }
  })
  return route
}